package com.myserver.core;

import java.io.*;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * 请求分发
 * @author Administrator
 */
public class Dispatcher extends Thread {
    private Request request;
    private Response response;
    private final Logger logger  = Logger.getLogger("console");
    public Dispatcher(Socket socket){
        try {
            logger.info("封装request");
            request = new Request(socket.getInputStream());
            logger.info("封装response");
            response = new Response(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        String reqUrl = request.getUrl();
        if(reqUrl!=null&&reqUrl.endsWith(".html")){
            pushHtml(reqUrl);
            return;
        }
        /*根据请求url找到servlet处理*/
        logger.info("获取servlet");
        Servlet servlet = ServletContext.getServlet(reqUrl);
        /*未找到返回404*/

        if(servlet==null){
            logger.warning("未找到对应servlet");
            response.flush(404);
        }else {
            /*调用servlet处理请求*/
            try {
                logger.info("调用servlet");
                servlet.service(request, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*返回客户端*/
            response.flush(200);
        }
    }
    private void pushHtml(String reqUrl) {
        logger.info("返回Html文件");
        String htmlFile = ServletContext.getContextPath() + ServletContext.getStaticPath() + reqUrl.substring(reqUrl.lastIndexOf("/") + 1);
        try (InputStream is = new FileInputStream(htmlFile);
             BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            StringBuilder sb = new StringBuilder();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            response.println(sb.toString());
            response.flush(200);
        } catch (IOException e) {
            e.printStackTrace();
            response.flush(404);
        }
    }
}
